Java Break

    Java Break statement

    The flow of the code will immediately be terminated whenever a break statement is encountered within a loop and resumes control at the next statement to the loop block. The break statement will break the flow of the program at a given condition.

    If you mentioned the break statement within the inner loop, the control only comes out of the inner loop. Break statement works with all types of loop statements.

    Syntax

    jump-statement;    
    break;   
    • Break Statement with the for Loop

    Example

    public class BreakExample {  
    
    public static void main(String[] args) {  
    
        //using for loop  
    
        for(int i=1;i<=5;i++){  
    
            if(i==4){   
    
                break;  
    
            }  
    
            System.out.println(i);  
    
        }  
    
    }  
    
    }  

    Output

    1
    2
    3
    • Break Statement with the Inner Loop

    Example

    public class Example2 {  
    
    public static void main(String[] args) {  
    
                for(int i=1;i<=3;i++){    
    
                        for(int j=1;j<=3;j++){    
    
                            if(i==2&&j==2){    
    
                                break;    
    
                            }    
    
                            System.out.println(i+" "+j);    
    
                        }    
    
                }    
    
    }  
    
    }  

    Output

    1 1
    1 2
    1 3
    2 1
    3 1
    3 2
    3 3
    • Break Statement with a while Loop

    Example-

    public class BreakWhileExample {  
    
    public static void main(String[] args) {  
    
        int i=1;  
    
        while(i<=10){  
    
            if(i==5){  
    
                i++;  
    
                break;
    
            }  
    
            System.out.println(i);  
    
            i++;  
    
        }  
    
    }  
    
    }  

    Output

    1
    2
    3
    4
    • Break Statement with a do-while Loop

    Example

    public class BreakDoWhileExample {  
    
    public static void main(String[] args) {  
    
        int i=1;  
    
        do{  
    
            if(i==5){  
    
               i++;  
    
               break;
    
            }  
    
            System.out.println(i);  
    
            i++;  
    
        }while(i<=10);  
    
    }  
    
    }  

    Output

    1
    2
    3
    4